import CryptoJS from "crypto-js"
const secretKey = 'your-aes-16byte-key-1234';  // AES 密钥
const hmacKey = 'your-aes-16byte-key-1234';  // HMAC 密钥

export interface dataToSend {
    encryptedMessage: string,
    hmac: string
}
export const getEncryptionMessage = (s: string): dataToSend => {
    // 生成随机 IV（初始化向量）
    const iv = CryptoJS.lib.WordArray.random(16);
    // 加密
    const encrypted = CryptoJS.AES.encrypt(CryptoJS.enc.Utf8.parse(s), CryptoJS.enc.Utf8.parse(secretKey), {
        iv: iv,
        mode: CryptoJS.mode.CBC,
        padding: CryptoJS.pad.Pkcs7
    });

    // 将 IV 和密文拼接
    const result = iv.concat(encrypted.ciphertext);

    // 计算 HMAC (使用密文 + IV 作为 HMAC 的数据)
    const hmac = CryptoJS.HmacSHA256(result, hmacKey).toString(CryptoJS.enc.Base64);

    // 返回加密后的密文和 HMAC
    return { encryptedMessage: CryptoJS.enc.Base64.stringify(result), hmac: hmac };
}
export const getDecryptMessage = (s: dataToSend): string => {
    const encryptedMessage = s.encryptedMessage;
    const receivedHMAC = s.hmac;

    // 验证 HMAC
    const computedHMAC = computeHMAC(encryptedMessage);
    if (computedHMAC !== receivedHMAC) {
        console.log("HMAC 验证失败！");
        return "";
    }
    // 解密消息
    return decryptMessage(encryptedMessage);
}

// AES 解密函数
function decryptMessage(encryptedMessage: string) {
    // Base64 解码
    const decodedMessage = CryptoJS.enc.Base64.parse(encryptedMessage);

    // 提取 IV（前 16 字节）
    const iv = decodedMessage.clone().words.slice(0, 4);  // 获取前 16 字节作为 IV
    // 提取密文（剩余部分）
    const ciphertext = decodedMessage.clone().words.slice(4);  // 获取剩余的密文部分

    // 使用 CryptoJS.lib.WordArray.create 创建密文和 IV
    const ivWordArray = CryptoJS.lib.WordArray.create(iv);
    const ciphertextWordArray = CryptoJS.lib.WordArray.create(ciphertext);

    // 创建 CipherParams 对象，确保传递 iv 和 ciphertext
    const cipherParams = CryptoJS.lib.CipherParams.create({
        ciphertext: ciphertextWordArray,
        iv: ivWordArray  // 确保 iv 被正确传递
    });

    // 使用 AES 解密（CBC 模式）
    const decrypted = CryptoJS.AES.decrypt(cipherParams, CryptoJS.enc.Utf8.parse(secretKey), {
        mode: CryptoJS.mode.CBC,
        padding: CryptoJS.pad.Pkcs7,
        iv: ivWordArray
    });

    // 解密结果转成 UTF-8 字符串
    const plaintext = decrypted.toString(CryptoJS.enc.Utf8);
    return plaintext;
}

// HMAC 计算函数
function computeHMAC(message: string) {
    const hmac = CryptoJS.HmacSHA256(message, hmacKey);
    return hmac.toString(CryptoJS.enc.Base64);
}

export interface WebSocketProps {
    url: string; // websocket地址
    heartTime: number; // 心跳时间间隔，默认为 50000 ms
    heartMsg: string; // 心跳信息，默认为'ping'
    reconnectCount: number; // 重连次数，默认为 5
    reconnectTime: number; // 重连时间间隔，默认为 10000 ms
    // webSocket 对象
    webSocket: WebSocket | null,
    // webSocket定时器id
    setIntervalId: any,
    falg: boolean,
    // 重连定时器id
    reconnectId: any
    socket_id: string
}

// 向后端发送的消息
export interface sendFace {
    type: number,
    account_uuid: string
    data: string
}

// ServiceMessage 接受后端发送的消息
export interface reqServiceMessage {
    type: number                   // 类型
    data: string
    body: ServiceMessageContent
}
export interface ServiceMessageContent {
    code: number
    message: string,
    data?: any
}
export enum websoctkeTypes {
    MessageTypeHeartbeat = 1, // 心跳
    MessageTypeRegister = 2,// 注册
    // HeartbeatCheckTime = '9' , // 心跳检测几秒检测一次
    // HeartbeatTime      = '20' ,// 心跳距离上一次的最大时间
    NotificationMessage = 99, // 通知加入房间
    SysHi = 101,
    SendMessage = 102, //发送房间消息
    AddRoom = 103, // 加入房间
    LeftRoom = 104, // 退出房间
    SysErr = 500
}


// SenderUUID   string     `gorm:"column:sender_uuid;type:varchar(255);not null;comment:发送者的uuid" json:"sender_uuid"`
// ReceiverUUID string     `gorm:"column:receiver_uuid;type:varchar(255);comment:接收者的uuid" json:"receiver_uuid"`
// GroupID      int32      `gorm:"column:group_id;type:int(11);comment:群聊的id" json:"group_id"`
// Content      string     `gorm:"column:content;type:text;comment:消息内容（如果是文本）" json:"content"`
// MediaURL     string     `gorm:"column:media_url;type:varchar(255);comment:媒体文件的url" json:"media_url"`
// MessageType  string     `gorm:"column:message_type;type:enum('text','image','video','file','audio','link');default:text;comment:消息类型" json:"message_type"`
// ChatType     string     `gorm:"column:chat_type;type:enum('one_to_one','group');default:one_to_one;comment:消息发送类型" json:"chat_type"`
// IsRead       bool       `gorm:"column:is_read;type:tinyint(1);comment:是否已读状态" json:"is_read"`
// IsRetracted  bool       `gorm:"column:is_retracted;type:tinyint(1);comment:是否已撤回" json:"is_retracted"`
export enum MessageType {
    text = "text",
    image = "image",
    video = "video",
    file = "file",
    audio = "audio",
    link = "link",
}
export enum ChatType {
    one_to_one = "one_to_one",
    group = "group",
}
export interface ChatMessageFace {
    sender_uuid: string;
    receiver_uuid?: string;
    group_id?: number;
    content: string;
    media_url?: string
    message_type: MessageType
    chat_type: ChatType
}
export interface serverMessage {
    content: string
    create_time: string
    nick_name: string
    picture: string
    user_uuid: string
}